<template>
  <basic-dialog
    title="创建账户"
    :visible="visible"
    :loading="loading"
    :width="448"
    has-footer
    @open="handleOpen"
    @closed="handleClose"
    @submit="handleSubmit"
  >
    <el-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      require-asterisk-position="right"
      label-width="100px"
      label-position="top"
      @submit.prevent
    >
      <el-form-item prop="email" label="邮箱">
        <el-input v-model="formState.email" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="账号类型" prop="type">
        <el-select v-model="formState.type" class="w-full">
          <el-option
            v-for="item in ACCOUNT_TYPE_OPTS"
            :key="item.label"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="密钥算法" prop="key_type">
        <el-select v-model="formState.key_type" class="w-full">
          <el-option
            v-for="item in ALGORITHM_OPTS"
            :key="item.label"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </basic-dialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormItemRule } from 'element-plus'

import type { CreateAcmeParams } from '@/apis/model/acme'
import { ACCOUNT_TYPE_OPTS, ALGORITHM_OPTS } from '@/config/constant/cert'

interface IProps {
  visible: boolean
  loading: boolean
}
interface IEmits {
  (event: 'update:visible', value: boolean): void
  (event: 'update:loading', value: boolean): void
  (event: 'refresh'): void
}

defineProps<IProps>()
const emit = defineEmits<IEmits>()
const formRef = ref<FormInstance>()

const formState = reactive<CreateAcmeParams>({
  email: '',
  type: 'letsencrypt',
  key_type: 'P256'
})

const rules: Record<string, FormItemRule[]> = {
  email: [
    { required: true, message: '输入', trigger: 'blur' },
    {
      type: 'email',
      message: '邮箱格式错误'
    }
  ],
  type: [{ required: true, message: '请选择', trigger: 'change' }],
  key_type: [{ required: true, message: '请选择', trigger: 'change' }]
}
const handleOpen = () => {}
const handleClose = () => {
  formRef.value?.resetFields()
  emit('update:visible', false)
}
async function handleSubmit() {
  await formRef.value?.validate()
  emit('update:loading', true)
  createAcmeApi(formState)
    .then(() => {
      handleClose()
      emit('refresh')
      ToastUtils.success('操作成功')
    })
    .finally(() => emit('update:loading', false))
}
</script>

<style lang="scss" scoped></style>
